﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using Tss.MagicWeb.Domain.Abstract;
using Tss.MagicWeb.Domain.Entities;
using Tss.MagicWeb.Domain.Infrastructure.Auth;
using Tss.MagicWeb.Filters;
using Tss.MagicWeb.Kernel.Utility;
using Tss.MagicWeb.ViewModels;

namespace Tss.MagicWeb.Controllers
{
    [AuthenticationFilter(false)]
    public class AccountController : Controller
    {
        public override string Name
        {
            get
            {
                return "Account";
            }
        }
        //
        // GET: /Account/

        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Login(FormCollection form)
        {
            string login = Request.Form["login"];
            string password = Request.Form["password"];
            string returnUrl = Request.Form["returnUrl"];

            var model = new LoginModel
            {
                Login = Request.Form["login"],
                Password = Request.Form["password"],
                Errors = new Dictionary<string, string> {},
            };

            User test =  ((IUserRepository) DependencyResolver.Current.GetService(typeof (IUserRepository))).ReadByLogin(login);

            if (test == null)
            {
                model.Errors.Add("login", "User login is incorrect");
                return View("Login", model);
            }

            var passwordIsValid = SecurityUtils.IsValid(password, test.Password, test.Salt);

            if (!passwordIsValid)
            {
                model.Errors.Add("password", "Password is incorrect");
                return View("Login", model);
            }
            
            LoginUtils.SignIn(test, false);
            return RedirectToAction("Index", "Home");
        }


        public ActionResult Logout()
        {
            LoginUtils.SignOut(HttpContext);
            return RedirectToAction("Index", "Home");
        }

    }
}
